{% extends "base.html" %}

{% block content %}
<div class="card">
    <h2>Import from Notion</h2>
    <p>Successfully connected to your Notion workspace: <strong>{{ workspace_name }}</strong></p>
    
    <div id="search-section" style="margin-top: 1.5rem;">
        <h3>Search Pages</h3>
        <div class="form-group">
            <input type="text" id="search-input" placeholder="Search for pages, journals, notes..." style="margin-bottom: 1rem;">
            <button onclick="searchNotion()" class="btn">Search</button>
        </div>
        
        <div id="search-loading" class="loading">
            Searching Notion...
        </div>
        
        <div id="search-results" style="margin-top: 1.5rem;">
            <!-- Search results will be displayed here -->
        </div>
    </div>
    
    <div id="extraction-section" style="margin-top: 2rem; display: none;">
        <h3>Extract Memories</h3>
        <p id="extraction-page-title">Page: <strong></strong></p>
        
        <div class="form-group">
            <button onclick="extractMemories()" class="btn">Extract Memories</button>
        </div>
        
        <div id="extraction-loading" class="loading">
            Extracting memories...
        </div>
        
        <div id="extraction-results" style="margin-top: 1.5rem;">
            <!-- Extraction results will be displayed here -->
        </div>
    </div>
    
    <div id="import-section" style="margin-top: 2rem; display: none;">
        <h3>Import to OMI</h3>
        <p>Review and import extracted memories to OMI.</p>
        
        <div class="form-group">
            <button onclick="importToOmi()" class="btn btn-secondary">Import to OMI</button>
        </div>
        
        <div id="import-loading" class="loading">
            Importing to OMI...
        </div>
        
        <div id="import-results" style="margin-top: 1.5rem;">
            <!-- Import results will be displayed here -->
        </div>
    </div>
</div>

<div class="card">
    <h2>Memories</h2>
    <p>View your extracted memories and their status.</p>
    
    <div class="form-group">
        <button onclick="loadMemories()" class="btn">Refresh Memories</button>
    </div>
    
    <div id="memories-loading" class="loading">
        Loading memories...
    </div>
    
    <ul id="memories-list" class="memory-list">
        <!-- Memories will be displayed here -->
    </ul>
    
    <div id="no-memories" style="text-align: center; margin-top: 1.5rem; display: none;">
        <p>No memories found. Extract memories from Notion to get started.</p>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    const uid = "{{ uid }}";
    let selectedPageId = "";
    let selectedPageTitle = "";
    let extractedMemories = [];
    
    // Search Notion
    async function searchNotion() {
        const searchQuery = document.getElementById('search-input').value;
        const searchLoading = document.getElementById('search-loading');
        const searchResults = document.getElementById('search-results');
        
        searchLoading.classList.add('active');
        searchResults.innerHTML = '';
        
        try {
            const response = await fetch('/api/notion/search', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    uid: uid,
                    query: searchQuery,
                    filter: {
                        property: 'object',
                        value: 'page'
                    }
                }),
            });
            
            const data = await response.json();
            
            if (data.results && data.results.length > 0) {
                searchResults.innerHTML = '<h4>Results</h4>';
                
                const resultsList = document.createElement('div');
                resultsList.className = 'search-results-list';
                
                data.results.forEach(page => {
                    const pageTitle = page.properties?.title?.title?.[0]?.plain_text || 
                                    page.properties?.Name?.title?.[0]?.plain_text || 
                                    'Untitled';
                    
                    const pageItem = document.createElement('div');
                    pageItem.className = 'memory-item';
                    pageItem.innerHTML = `
                        <strong>${pageTitle}</strong>
                        <button onclick="selectPage('${page.id}', '${pageTitle.replace(/'/g, "\\'")}')" class="btn" style="margin-top: 0.5rem;">Select</button>
                    `;
                    
                    resultsList.appendChild(pageItem);
                });
                
                searchResults.appendChild(resultsList);
            } else {
                searchResults.innerHTML = '<p>No results found. Try a different search term.</p>';
            }
        } catch (error) {
            console.error('Error searching Notion:', error);
            searchResults.innerHTML = '<p class="error-message">Error searching Notion. Please try again.</p>';
        } finally {
            searchLoading.classList.remove('active');
        }
    }
    
    // Select Page for Extraction
    function selectPage(pageId, pageTitle) {
        selectedPageId = pageId;
        selectedPageTitle = pageTitle;
        
        document.getElementById('extraction-section').style.display = 'block';
        document.getElementById('extraction-page-title').innerHTML = `Page: <strong>${pageTitle}</strong>`;
        
        // Scroll to extraction section
        document.getElementById('extraction-section').scrollIntoView({ behavior: 'smooth' });
    }
    
    // Extract Memories
    async function extractMemories() {
        if (!selectedPageId) {
            alert('Please select a page first');
            return;
        }
        
        const extractionLoading = document.getElementById('extraction-loading');
        const extractionResults = document.getElementById('extraction-results');
        
        extractionLoading.classList.add('active');
        extractionResults.innerHTML = '';
        
        const formData = new FormData();
        formData.append('uid', uid);
        formData.append('block_type', 'page');
        formData.append('block_id', selectedPageId);
        
        try {
            const response = await fetch('/api/notion/extract-memories', {
                method: 'POST',
                body: formData
            });
            
            const data = await response.json();
            
            if (data.success && data.memories && data.memories.length > 0) {
                extractedMemories = data.memories;
                
                extractionResults.innerHTML = `
                    <p class="success-message">Successfully extracted ${data.memories.length} memories</p>
                    <h4>Extracted Memories</h4>
                `;
                
                const memoriesList = document.createElement('ul');
                memoriesList.className = 'memory-list';
                
                data.memories.forEach(memory => {
                    const memoryItem = document.createElement('li');
                    memoryItem.className = 'memory-item pending';
                    memoryItem.innerHTML = `
                        <span class="status-badge pending">Pending</span>
                        ${memory}
                    `;
                    
                    memoriesList.appendChild(memoryItem);
                });
                
                extractionResults.appendChild(memoriesList);
                
                // Show import section
                document.getElementById('import-section').style.display = 'block';
            } else {
                extractionResults.innerHTML = '<p>No memories extracted. Try a different page.</p>';
            }
        } catch (error) {
            console.error('Error extracting memories:', error);
            extractionResults.innerHTML = '<p class="error-message">Error extracting memories. Please try again.</p>';
        } finally {
            extractionLoading.classList.remove('active');
        }
    }
    
    // Import to OMI
    async function importToOmi() {
        if (extractedMemories.length === 0) {
            alert('No memories to import');
            return;
        }
        
        const importLoading = document.getElementById('import-loading');
        const importResults = document.getElementById('import-results');
        
        importLoading.classList.add('active');
        importResults.innerHTML = '';
        
        try {
            const response = await fetch('/api/omi/process-pending-memories/' + uid, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            });
            
            const data = await response.json();
            
            if (data.processed > 0) {
                importResults.innerHTML = `
                    <p class="success-message">Successfully imported ${data.processed} memories to OMI</p>
                `;
                
                // Refresh memories list
                loadMemories();
            } else {
                importResults.innerHTML = '<p>No memories imported. Please try again.</p>';
            }
        } catch (error) {
            console.error('Error importing to OMI:', error);
            importResults.innerHTML = '<p class="error-message">Error importing memories to OMI. Please try again.</p>';
        } finally {
            importLoading.classList.remove('active');
        }
    }
    
    // Load Memories
    async function loadMemories() {
        const memoriesLoading = document.getElementById('memories-loading');
        const memoriesList = document.getElementById('memories-list');
        const noMemories = document.getElementById('no-memories');
        
        memoriesLoading.classList.add('active');
        memoriesList.innerHTML = '';
        noMemories.style.display = 'none';
        
        try {
            const response = await fetch('/api/omi/memories/' + uid);
            const data = await response.json();
            
            if (data.memories && data.memories.length > 0) {
                data.memories.forEach(memory => {
                    const memoryItem = document.createElement('li');
                    memoryItem.className = `memory-item ${memory.status}`;
                    
                    const statusText = memory.status === 'pending' ? 'Pending' : 
                                     memory.status === 'completed' ? 'Imported' : 'Failed';
                    
                    memoryItem.innerHTML = `
                        <span class="status-badge ${memory.status}">${statusText}</span>
                        ${memory.memory_text}
                    `;
                    
                    memoriesList.appendChild(memoryItem);
                });
            } else {
                noMemories.style.display = 'block';
            }
        } catch (error) {
            console.error('Error loading memories:', error);
            memoriesList.innerHTML = '<p class="error-message">Error loading memories. Please try again.</p>';
        } finally {
            memoriesLoading.classList.remove('active');
        }
    }
    
    // Load memories on page load
    document.addEventListener('DOMContentLoaded', loadMemories);
</script>
{% endblock %} 